import { useModel } from '@umijs/max';
import {
  Form, Input, Select, Button, InputNumber, Popconfirm,
  Table, Image, Switch, Space, message, Tabs,
  Upload, Radio, Checkbox
} from 'antd';
import {
  SearchOutlined, ReloadOutlined, EditOutlined,
  DeleteOutlined, PlusOutlined, DownloadOutlined, LeftOutlined,
  UploadOutlined, PlayCircleOutlined, DeleteOutlined as DeleteIcon
} from '@ant-design/icons';
import React, { useState, useEffect, useRef } from 'react';
import type { TableProps, TabsProps, UploadProps } from 'antd';
import './module.goodslist.css'
import { dataList, dataAdd, dataDel, dataState, imageFile } from '@/api/goodslist';
import UEditor from '@/components/ueditor';

const { Option } = Select;
const { TextArea } = Input;
import { path } from '@/config/index';


// 定义商品分类类型
interface CategoryType {
  value: number;
  label: string;
}

// 定义商品数据类型
interface GoodsType {
  id: string | number;
  key: string;
  img: string;
  title: string;
  price: number;
  original_price?: number;
  stock: number;
  sales: number;
  status: number; // 1:上架, 0:下架
  sort: number;
  descriptiones?: string;
  category?: string;
  spec?: string;
  recommendation?: string;
  goods_type_id?: number;
  synopsis?: string;
  unit?: string;
  shipAddress?: string;
  shippingFee?: number;
  keywords?: string;
  type?: number; // 1:单规格, 0:多规格
  norm?: string; // 多规格可选规格json数组
  norm_arr?: string; // 多规格所有规格json数组
  params?: string;
}

// 分页响应数据类型
interface PaginationResponse {
  current: number;
  pageSize: number;
  total: number;
  records: GoodsType[];
  type: CategoryType[];
}

// 规格项类型
interface Specification {
  id: number;
  name: string;
  price: string;
  originalPrice: string;
  stock: string;
  image: any;
}

const GoodsList: React.FC = () => {
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [data, setData] = useState<GoodsType[]>([]);
  const [categories, setCategories] = useState<CategoryType[]>([]);
  const [loading, setLoading] = useState(false);
  const [editingKey, setEditingKey] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 100,
    total: 0,
  });
  // 新增/编辑表单相关状态
  const [currentView, setCurrentView] = useState<'list' | 'add' | 'edit'>('list'); // 'list' 或 'add' 或 'edit'
  const [currentStep, setCurrentStep] = useState(0);
  const [tabActiveKey, setTabActiveKey] = useState('1');
  const [fileList, setFileList] = useState<any[]>([]);
  const [mainImageFileList, setMainImageFileList] = useState<any[]>([]); // 单图（主图）
  const [detailImageFileList, setDetailImageFileList] = useState<any[]>([]); // 多图（详情图）
  const [videoFile, setVideoFile] = useState<any>(null);
  const [showVideoUpload, setShowVideoUpload] = useState(false); // 控制视频上传显示隐藏
  const ueditorRef1 = useRef<any>(null);
  const ueditorRef2 = useRef<any>(null);
  // 当前编辑的商品ID
  const [currentGoodsId, setCurrentGoodsId] = useState<number | string | null>(null);
  // 多规格
  const [specType, setSpecType] = useState<'single' | 'multiple'>('single');
  const [specifications, setSpecifications] = useState<Specification[]>([
    { id: 1, name: '', price: '', originalPrice: '', stock: '', image: null }
  ]);
  const [specInputs, setSpecInputs] = useState<{ id: number, value: string }[]>([
    { id: 1, value: '' }
  ]);
  // 修复自定义上传请求，确保返回正确的URL结构
  const customUploadRequest = async (options: any) => {
    const { onSuccess, onError, file, onProgress } = options;

    try {
      const formData = new FormData();
      formData.append('file', file);
      console.log(file);


      const response = await imageFile(formData, {
        onUploadProgress: (progressEvent) => {
          if (progressEvent.total) {
            const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            onProgress({ percent });
          }
        }
      });

      if (response.code === 1) {
        // 根据您的接口返回结构调整 - 确保获取正确的URL
        const fileUrl = response.data?.url || response.data?.path || response.url;

        if (!fileUrl) {
          throw new Error('上传接口返回的URL为空');
        }

        onSuccess({
          url: fileUrl,
          name: file.name,
          status: 'done'
        }, file);
      } else {
        onError(new Error(response.msg || '上传失败'));
      }
    } catch (error) {
      console.error('上传错误:', error);
      onError(error);
    }
  };

  // 处理主图上传
  const handleMainImageUpload: UploadProps['onChange'] = (info) => {
    let newFileList = [...info.fileList];
    newFileList = newFileList.slice(-1);

    // 处理上传响应 - 确保URL正确设置
    newFileList = newFileList.map(file => {
      if (file.response) {
        // 确保从响应中正确获取URL
        file.url = file.response.data?.url || file.response.url || file.response.data?.path;
      }
      // 如果是本地上传但尚未完成，保留文件信息
      if (file.status === 'uploading' || file.status === 'done') {
        file.url = file.url || file.thumbUrl;
      }
      return file;
    });

    setMainImageFileList(newFileList);
  };

  // 详情图（多图）上传处理
  const handleDetailImageUpload: UploadProps['onChange'] = (info) => {
    let newFileList = [...info.fileList];
    newFileList = newFileList.slice(-5);

    newFileList = newFileList.map(file => {
      if (file.response) {
        // 确保从响应中正确获取URL
        file.url = file.response.data?.url || file.response.url || file.response.data?.path;
      }
      // 如果是本地上传但尚未完成，保留文件信息
      if (file.status === 'uploading' || file.status === 'done') {
        file.url = file.url || file.thumbUrl;
      }
      return file;
    });

    setDetailImageFileList(newFileList);
  };
  // 视频上传处理
  const handleVideoUpload = (info: any) => {
    setVideoFile(info.file);
  };

  // 删除视频
  const handleDeleteVideo = () => {
    setVideoFile(null);
  };

  // 获取商品列表数据
  const fetchGoodsList = async (pageParams = { current: 1, pageSize: 100 }, searchParams = {}) => {
    setLoading(true);
    try {
      // 合并分页参数和搜索参数
      const params = {
        current: pageParams.current,
        pageSize: pageParams.pageSize,
        ...searchParams
      };

      const response = await dataList(params);
      console.log('接口响应:', response);

      if (response.code === 1) {
        const records = response.data.list;
        const categoryData = response.data.type || [];

        const goodsData = Array.isArray(records) ? records.map((item: any) => ({
          ...item,
          key: item.id?.toString() || Math.random().toString(),
        })) : [];

        setData(goodsData);
        setCategories(categoryData);

        // 更新分页信息
        setPagination({
          current: response.data?.current || pageParams.current,
          pageSize: response.data?.pageSize || pageParams.pageSize,
          total: response.data?.total || 0,
        });
      } else {
        message.error(response.msg || '获取商品列表失败');
      }
    } catch (error) {
      console.error('获取商品列表失败:', error);
      message.error('获取商品列表失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchGoodsList({ current: 1, pageSize: 100 });
  }, []);

  // 搜索处理
  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    // 构建符合接口要求的搜索参数
    const searchParams = {
      title: values.name, // 商品名称
      keyword: values.keyword, // 关键字
      synopsis: values.description, // 商品简介
      type: values.specType, // 规格
      recommend: values.recommendation, // 推荐
      goods_type_id: values.category // 商品分类id
    };

    // 过滤掉空值
    const filteredParams = Object.fromEntries(
      Object.entries(searchParams).filter(([_, value]) => value !== undefined && value !== '')
    );

    setSelectedRowKeys([]);
    // 重置到第一页进行搜索
    fetchGoodsList({ current: 1, pageSize: pagination.pageSize }, filteredParams);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    // 重置后回到第一页
    fetchGoodsList({ current: 1, pageSize: pagination.pageSize });

    setSelectedRowKeys([]);
  };

  // 表格分页变化处理
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    const values = searchForm.getFieldsValue();
    // 构建符合接口要求的搜索参数
    const searchParams = {
      title: values.name,
      keyword: values.keyword,
      synopsis: values.description,
      type: values.specType,
      recommend: values.recommendation,
      goods_type_id: values.category
    };

    // 过滤掉空值
    const filteredParams = Object.fromEntries(
      Object.entries(searchParams).filter(([_, value]) => value !== undefined && value !== '')
    );

    fetchGoodsList(
      {
        current: pagination.current,
        pageSize: pagination.pageSize
      },
      filteredParams
    );
  };

  // 上下架状态切换
  const handleStatusChange = async (id: string | number, status: number) => {
    try {
      const response = await dataState({ ids: id, status: status === 1 ? 0 : 1 });
      if (response.code === 1) {
        message.success('状态更新成功');
        fetchGoodsList(
          { current: pagination.current, pageSize: pagination.pageSize },
          searchForm.getFieldsValue()
        );
      } else {
        message.error(response.msg || '状态更新失败');
      }
    } catch (error) {
      console.error('修改状态失败:', error);
      message.error('状态更新失败');
    }
  };

  // 删除商品
  const handleDelete = async (id: string | number, goods_type_id: any) => {
    try {
      // 处理 goods_type_id，如果是数组则取第一个元素，如果是数字则直接使用
      const typeId = Array.isArray(goods_type_id)
        ? goods_type_id[0]  // 取数组的第一个元素
        : Number(goods_type_id); // 如果不是数组，转换为数字
      const response = await dataDel({
        ids: id,
        goods_type_id: typeId
      });

      if (response.code === 1) {
        message.success('删除成功');
        fetchGoodsList(
          { current: pagination.current, pageSize: pagination.pageSize },
          searchForm.getFieldsValue()
        );
      } else {
        message.error(response.msg || '删除失败');
        console.log(id, response, typeId);
      }
    } catch (error) {
      console.error('删除商品失败:', error);
      message.error('删除失败');
    }
  };


  // 批量删除
  const handleBatchDelete = async () => {

    try {
      // 获取选中商品的 goods_type_id（假设所有选中商品属于同一分类）
      const selectedGoods = data.filter(item => selectedRowKeys.includes(item.key));
      const goodsTypeIds = selectedGoods.map(item => item.goods_type_id);

      // 取第一个商品的分类ID（假设批量操作的商品都属于同一分类）
      const firstTypeId = goodsTypeIds.length > 0
        ? (Array.isArray(goodsTypeIds[0]) ? goodsTypeIds[0][0] : Number(goodsTypeIds[0]))
        : null;

      if (!firstTypeId) {
        message.error('无法确定商品分类');
        return;
      }

      const response = await dataDel({
        ids: selectedRowKeys.join(','),
        goods_type_id: firstTypeId
      });

      if (response.code === 1) {
        message.success('批量删除成功');
        setSelectedRowKeys([]);
        fetchGoodsList(
          { current: pagination.current, pageSize: pagination.pageSize },
          searchForm.getFieldsValue()
        );
      } else {
        message.error(response.msg || '批量删除失败');
        console.log(selectedRowKeys.join(','), response, firstTypeId);
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      message.error('批量删除失败');
    }
  };

  // 图片上传处理
  const handleImageUpload: UploadProps['onChange'] = (info) => {
    let newFileList = [...info.fileList];
    newFileList = newFileList.slice(-6); // 限制最多6张图片
    setFileList(newFileList);
  };

  // 表格列定义
  const columns: TableProps<GoodsType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      width: 60,
      render: (_, __, index) => index + 1 + (pagination.current - 1) * pagination.pageSize,
    },
    {
      title: '商品图片',
      dataIndex: 'img',
      align: 'center',
      width: 100,
      render: (img) => (
        <Image
          width={50}
          height={50}
          src={img}
          alt="商品图片"
          style={{ objectFit: 'cover' }}
        />
      ),
    },
    {
      title: '商品名称',
      align: 'center',
      dataIndex: 'title',
      width: 120,
      ellipsis: true,
    },
    {
      title: '售价',
      align: 'center',
      dataIndex: 'price',
      width: 100,
      render: (price) => price ? `¥${Number(price).toFixed(2)}` : '¥0.00',
    },
    {
      title: '库存',
      align: 'center',
      dataIndex: 'stock',
      width: 80,
      render: (stock) => stock || 0,
    },
    {
      title: '销量',
      align: 'center',
      dataIndex: 'sales',
      width: 80,
      render: (sales) => sales || 0,
    },
    {
      title: '上下架',
      align: 'center',
      dataIndex: 'status',
      width: 100,
      render: (status, record) => (
        <Switch
          checked={status === 1}
          onChange={(checked) => handleStatusChange(record.id, checked ? 1 : 0)}
          checkedChildren="上架"
          unCheckedChildren="下架"
        />
      ),
    },
    {
      title: '排序',
      align: 'center',
      dataIndex: 'sort',
      width: 80,
      render: (sort) => sort || 0,
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'operation',
      width: 120,
      fixed: 'right' as const,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            style={{ padding: '0 4px', border: '1px solid #1890ff' }}
            icon={<EditOutlined />}
            onClick={() => edit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个商品吗？"
            onConfirm={() => handleDelete(record.id, record.goods_type_id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              size="small"
              style={{ padding: '0 4px', border: '1px solid #ff4d4f' }}
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const isEditing = (record: GoodsType) => record.key === editingKey;

  // 新增表单相关函数
  const showAddView = () => {
    setCurrentView('add');
    setCurrentStep(0);
    setTabActiveKey('1');
    setCurrentGoodsId(null);
    form.resetFields();
    setFileList([]);
    setVideoFile(null);
    setMainImageFileList([]);
    setDetailImageFileList([]);
    setSpecType('single');
    setSpecifications([{ id: 1, name: '', price: '', originalPrice: '', stock: '', image: null }]);
    setSpecInputs([{ id: 1, value: '' }]);
  };

  const showListView = () => {
    setCurrentView('list');
    setCurrentStep(0);
    setTabActiveKey('1');
    form.resetFields();
  };

  // 下一步按钮点击
  const handleNext = async () => {
    try {
      // 根据当前步骤验证对应的表单字段
      const fieldsToValidate = getFieldsToValidate(currentStep);
      await form.validateFields(fieldsToValidate);

      // 特殊校验：第一步需要校验图片上传
      if (currentStep === 0) {
        if (mainImageFileList.length === 0) {
          message.error('请上传商品主图');
          return;
        }
        if (detailImageFileList.length === 0) {
          message.error('请上传轮播图');
          return;
        }
      }

      // 特殊校验：第二步规格库存校验
      if (currentStep === 1) {
        if (specType === 'multiple') {
          // 校验多规格数据
          const invalidSpecs = specifications.filter(spec =>
            !spec.price || !spec.originalPrice || !spec.stock
          );
          if (invalidSpecs.length > 0) {
            message.error('请完善所有规格的价格和库存信息');
            return;
          }
        }
      }

      if (currentStep < 5) {
        setCurrentStep(currentStep + 1);
        setTabActiveKey(String(currentStep + 2));
      }
    } catch (error) {
      console.log('验证失败:', error);
      message.error('请完善当前步骤的信息');
    }
  };

  // 上一步按钮点击
  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
      setTabActiveKey(String(currentStep));
    }
  };
  // 单独处理图片数据的函数
  const handleImageData = async (record: GoodsType) => {
    // 主图处理
    if (record.img) {
      const mainImageUrl = record.img.startsWith('http')
        ? record.img
        : `${path}${record.img}`;

      setMainImageFileList([{
        uid: '-1',
        name: 'main-image',
        url: mainImageUrl,
        status: 'done',
        thumbUrl: mainImageUrl,
      }]);
    }

    // 轮播图处理
    if (record.imgs) {
      const detailImages = Array.isArray(record.imgs)
        ? record.imgs
        : (record.imgs.split(',').filter(img => img.trim() !== ''));

      const detailFileList = detailImages.map((img: string, index: number) => {
        const imageUrl = img.startsWith('http') ? img : `${path}${img}`;
        return {
          uid: `detail-${index}`,
          name: `detail-image-${index}`,
          url: imageUrl,
          status: 'done',
          thumbUrl: imageUrl,
        };
      });

      setDetailImageFileList(detailFileList);
    }

    // 视频文件处理（如果有的话）
    if (record.video) {
      const videoUrl = record.video.startsWith('http')
        ? record.video
        : `${path}${record.video}`;

      setVideoFile({
        uid: '-video',
        name: 'product-video',
        url: videoUrl,
        status: 'done',
      });
    }
  };
  const handleSpecData = async (record: GoodsType) => {
    // 明确判断规格类型，1为单规格，0为多规格
    const isSingle = record.type === 1;

    // 立即设置规格类型状态
    setSpecType(isSingle ? 'single' : 'multiple');

    // 同步设置表单中的规格类型值
    form.setFieldsValue({
      specType: isSingle ? 'single' : 'multiple'
    });
    if (isSingle) {
      // 单规格处理 - 修复数据回显
      const priceValue = record.price || 0;
      const originalPriceValue = record.original_price || 0;
      const stockValue = record.stock || 0;

      console.log('单规格数据回显:', { priceValue, originalPriceValue, stockValue });

      // 使用setTimeout确保表单已准备好接收数据
      setTimeout(() => {
        form.setFieldsValue({
          price: priceValue,
          originalPrice: originalPriceValue,
          stock: stockValue,
        });
      }, 0);

      // 清空多规格数据
      setSpecInputs([{ id: 1, value: '' }]);
      setSpecifications([{ id: 1, name: '', price: '', originalPrice: '', stock: '', image: null }]);
    } else {
      // 多规格处理 - 增强图片处理逻辑
      try {
        let normData = [];
        let normArrData = [];

        // 解析规格数据
        if (record.norm) {
          normData = typeof record.norm === 'string'
            ? JSON.parse(record.norm)
            : record.norm;
        }

        if (record.norm_arr) {
          normArrData = typeof record.norm_arr === 'string'
            ? JSON.parse(record.norm_arr)
            : record.norm_arr;
        }

        normData = Array.isArray(normData) ? normData : [];
        normArrData = Array.isArray(normArrData) ? normArrData : [];

        // 处理规格名称输入框
        if (normData.length > 0 && normData[0]?.value) {
          const specValues = Array.isArray(normData[0].value)
            ? normData[0].value
            : [normData[0].value].filter(Boolean);

          const specInputs = specValues.map((name: string, index: number) => ({
            id: index + 1,
            value: name || `规格${index + 1}`
          }));
          setSpecInputs(specInputs);

          // 处理规格详情数据
          const specifications = specValues.map((name: string, index: number) => {
            const specData = normArrData[index] || {};

            // 处理图片URL - 确保正确回显
            let imageObj = null;
            if (specData.img) {
              let imageUrl = specData.img;

              // 确保URL格式正确
              if (imageUrl && !imageUrl.startsWith('http')) {
                imageUrl = `${path}${imageUrl.startsWith('/') ? imageUrl : '/' + imageUrl}`;
              }

              imageObj = {
                uid: `spec-${index}-${Date.now()}`,
                name: `spec-image-${index}`,
                url: imageUrl,
                status: 'done' as const,
                thumbUrl: imageUrl,
              };
            }

            return {
              id: index + 1,
              name: name || `规格${index + 1}`,
              price: specData.price?.toString() || '',
              originalPrice: specData.original_price?.toString() || '',
              stock: specData.stock?.toString() || '',
              image: imageObj
            };
          });

          setSpecifications(specifications);
        } else {
          // 如果没有规格数据，设置默认值
          setSpecInputs([{ id: 1, value: '默认规格' }]);
          setSpecifications([{
            id: 1,
            name: '默认规格',
            price: record.price?.toString() || '',
            originalPrice: record.original_price?.toString() || '',
            stock: record.stock?.toString() || '',
            image: null
          }]);
        }
      } catch (error) {
        console.error('规格数据解析错误:', error);
        // 设置默认规格数据
        setSpecInputs([{ id: 1, value: '默认规格' }]);
        setSpecifications([{
          id: 1,
          name: '默认规格',
          price: record.price?.toString() || '',
          originalPrice: record.original_price?.toString() || '',
          stock: record.stock?.toString() || '',
          image: null
        }]);
      }
    }
  };
  const handleRichText = (record: GoodsType) => {
    // 使用 setTimeout 确保编辑器已初始化
    setTimeout(() => {
      if (ueditorRef1.current && record.content) {
        try {
          ueditorRef1.current.setContent(record.content);
        } catch (error) {
          console.error('设置商品详情失败:', error);
        }
      }

      if (ueditorRef2.current && record.params) {
        try {
          ueditorRef2.current.setContent(record.params);
        } catch (error) {
          console.error('设置商品参数失败:', error);
        }
      }
    }, 100);
  };


  const edit = async (record: GoodsType) => {
    console.log('编辑数据接收:', record);
    console.log('规格类型:', record.type);
    console.log('规格数据:', record.norm);
    console.log('规格数组:', record.norm_arr);
    try {
      // 先重置所有状态
      setCurrentView('edit');
      setCurrentGoodsId(record.id);
      setCurrentStep(0);
      setTabActiveKey('1');

      // 重置所有文件列表
      setFileList([]);
      setVideoFile(null);
      setMainImageFileList([]);
      setDetailImageFileList([]);

      // 先设置规格类型状态
      const isSingle = record.type === 1;
      setSpecType(isSingle ? 'single' : 'multiple');

      // 等待状态重置完成
      await new Promise(resolve => setTimeout(resolve, 0));

      let recommendValues = [];
      if (record.recommend) {
        // 如果是数组，直接使用；如果是字符串，尝试解析为数组
        if (Array.isArray(record.recommend)) {
          recommendValues = record.recommend;
        } else {
          try {
            recommendValues = JSON.parse(record.recommend);
          } catch (e) {
            // 如果解析失败，尝试按逗号分割
            recommendValues = record.recommend.split(',').filter(Boolean);
          }
        }
      }

      // 将数字值映射为复选框对应的字符串值
      const mappedRecommend = recommendValues.map(val => {
        const num = Number(val);
        switch (num) {
          case 1: return "hot";
          case 2: return "recommend";
          case 3: return "guess";
          default: return "";
        }
      }).filter(Boolean);

      // 设置表单基础数据
      form.setFieldsValue({
        goodsName: record.title || '',
        category: record.goods_type_id ? record.goods_type_id.join(',') : '',
        synopsis: record.synopsis || '',
        unit: record.unit,
        status: record.status ?? 1,
        sort: record.sort ?? 0,
        keywords: record.keyword || '',
        sales: record.sales || 0,
        descriptiones: record.content,
        params: record.params,
        shipAddress: record.shipping_address || '',
        shippingFee: record.shippingFee || 0,
        specType: record.type === 0 ? 'multiple' : 'single',
        recommendation: mappedRecommend
      });

      // 处理图片数据
      await handleImageData(record);

      // 处理规格数据
      await handleSpecData(record);

      // 处理富文本
      await handleRichText(record);

    } catch (error) {
      console.error('编辑回显失败:', error);
      // message.error('加载编辑数据失败');
    }
  };
  // 修复保存函数中的图片URL处理
  const handleSave = async () => {
    try {
      await form.validateFields();
      const formData = form.getFieldsValue();

      // 修正字段名以匹配接口要求
      const submitData: any = {
        title: formData.goodsName,
        goods_type_id: formData.category,
        synopsis: formData.synopsis,
        unit: formData.unit || '个',
        status: formData.status,
        sold: formData.sales || 0,
        sort: formData.sort,
        keyword: formData.keywords,
        shipping_address: formData.shipAddress,
        courier_fee: formData.shippingFee,
        type: specType === 'single' ? 1 : 0,
        content: ueditorRef1.current?.getContent() || '',
        params: ueditorRef2.current?.getContent() || '',
      };


      // 处理推荐类型（将字符串值转回数字，并用逗号分隔）
      if (formData.recommendation && formData.recommendation.length) {
        // 将复选框值映射为数字，过滤无效值，再用逗号拼接
        submitData.recommend = formData.recommendation
          .map(val => {
            switch (val) {
              case "hot": return 1;
              case "recommend": return 2;
              case "guess": return 3;
              default: return null; // 过滤无效值
            }
          })
          .filter(num => num !== null) // 移除空值
          .join(','); // 转为逗号分隔字符串，如 "1,2"
      } else {
        submitData.recommend = ''; // 无选择时为空字符串
      }

      // 处理图片URL - 确保获取完整的URL
      const mainImageUrl = mainImageFileList[0]?.url || mainImageFileList[0]?.response?.url;

      // 处理详情图URL - 确保每个URL都是完整的
      const detailImageUrls = detailImageFileList.map(img => {
        let url = img.url || img.response?.url;
        // 如果URL不是完整路径，添加基础路径
        if (url && !url.startsWith('http')) {
          url = `${path}${url.startsWith('/') ? url : '/' + url}`;
        }
        return url;
      }).filter(url => url);

      if (!mainImageUrl) {
        message.error('请上传商品主图');
        return;
      }

      if (detailImageUrls.length < 2) {
        message.error('请上传至少两张轮播图');
        return;
      }

      // 设置图片数据 - 确保格式正确
      submitData.img = mainImageUrl.startsWith('http') ? mainImageUrl : `${path}${mainImageUrl.startsWith('/') ? mainImageUrl : '/' + mainImageUrl}`;
      submitData.imgs = detailImageUrls.join(',');

      console.log('主图URL:', submitData.img);
      console.log('轮播图URLs:', submitData.imgs);

      // 处理规格数据...
      if (specType === 'multiple') {
        const invalidSpecs = specifications.filter(spec =>
          !spec.name || !spec.price || !spec.originalPrice || !spec.stock
        );

        if (invalidSpecs.length > 0) {
          message.error('请完善所有规格的名称、价格和库存信息');
          return;
        }

        // 构建规格数据，正确处理图片URL
        const normData = [{
          name: "规格",
          value: specifications.map(spec => spec.name).filter(name => name)
        }];

        const normArrData = specifications.map(spec => {
          // 提取图片URL，处理不同情况
          let imgUrl = '';
          if (spec.image) {
            // 优先使用已上传的图片URL
            imgUrl = spec.image.url || '';

            // 如果URL不是完整路径，添加基础路径
            if (imgUrl && !imgUrl.startsWith('http')) {
              imgUrl = `${path}${imgUrl.startsWith('/') ? imgUrl : '/' + imgUrl}`;
            }
          }

          return {
            img: imgUrl,
            price: spec.price,
            original_price: spec.originalPrice,
            stock: spec.stock
          };
        });

        submitData.norm = JSON.stringify(normData);
        submitData.norm_arr = JSON.stringify(normArrData);

        console.log('多规格图片数据:', normArrData.map(item => item.img));
      }

      // 添加ID用于编辑
      if (currentGoodsId) {
        submitData.id = currentGoodsId;
      }

      console.log('最终提交数据:', submitData);

      const response = await dataAdd(submitData);

      if (response.code === 1) {
        message.success(currentGoodsId ? '编辑成功' : '新增成功');
        showListView();
        fetchGoodsList({ current: pagination.current, pageSize: pagination.pageSize });
      } else {
        message.error(response.msg || (currentGoodsId ? '编辑失败' : '新增失败'));
      }
    } catch (error) {
      console.log('验证失败:', error);
      message.error('请检查表单必填项');
    }
  };


  // 根据步骤获取需要验证的字段
  const getFieldsToValidate = (step: number) => {
    const fieldMap = {
      0: ['goodsName', 'category', 'mainImage', 'detailImages', 'status', 'synopsis', 'unit'], // 基础信息
      1: ['specType', ...(specType === 'single' ? ['price', 'originalPrice', 'stock'] : [])], // 规格库存
      2: ['descriptiones'], // 商品详情
      3: ['params'], // 产品参数
      4: ['shipAddress', 'shippingFee'], // 物流设置
      5: ['sort', 'keywords', 'sales', 'recommendation'] // 营销设置
    };
    return fieldMap[step as keyof typeof fieldMap] || [];
  };

  // 选项卡切换 - 不进行验证
  const handleTabChange = (key: string) => {
    setTabActiveKey(key);
    setCurrentStep(Number(key) - 1);
  };

  // 添加新的规格输入框
  const addSpecInput = () => {
    const newId = specInputs.length > 0
      ? Math.max(...specInputs.map(input => input.id)) + 1
      : 1;

    setSpecInputs([
      ...specInputs,
      { id: newId, value: '' }
    ]);

    // 同时添加对应的表格行
    setSpecifications([
      ...specifications,
      { id: newId, name: '', price: '', originalPrice: '', stock: '', image: null }
    ]);
  };

  // 更新输入框的值
  const updateSpecInput = (id: number, value: string) => {
    setSpecInputs(specInputs.map(input =>
      input.id === id ? { ...input, value } : input
    ));

    // 同步更新表格中的规格名称
    updateSpecificationField(id, 'name', value);
  };

  // 删除规格输入框和对应的表格行
  const removeSpecInput = (id: number) => {
    if (specInputs.length > 1) {
      setSpecInputs(specInputs.filter(input => input.id !== id));
      setSpecifications(specifications.filter(spec => spec.id !== id));
    } else {
      message.warning('至少需要保留一个规格项');
    }
  };

  // 删除规格项
  const removeSpecification = (id: number) => {
    if (specifications.length > 1) {
      setSpecifications(specifications.filter(spec => spec.id !== id));
      setSpecInputs(specInputs.filter(input => input.id !== id));
    } else {
      message.warning('至少需要保留一个规格项');
    }
  };

  // 重置规格项
  const resetSpecification = (id: number) => {
    setSpecifications(specifications.map(spec =>
      spec.id === id ? { ...spec, price: '', originalPrice: '', stock: '', image: null } : spec
    ));
  };

  // 更新规格字段值
  const updateSpecificationField = (id: number, field: string, value: any) => {
    setSpecifications(specifications.map(spec =>
      spec.id === id ? {
        ...spec,
        [field]: field === 'name' ? value : String(value) // 确保非名称字段转为字符串
      } : spec
    ));
  };
  // 修复规格项图片上传处理函数
  const handleSpecificationImageUpload = (id: number, info: any) => {
    const { file } = info;

    if (file.status === 'uploading') {
      // 上传中状态
      updateSpecificationField(id, 'image', {
        uid: file.uid,
        name: file.name,
        status: 'uploading' as const,
        percent: file.percent
      });
    } else if (file.status === 'done') {
      // 上传成功 - 修复URL获取逻辑
      if (file.response) {
        let imgUrl = file.response.data?.url || file.response.data?.path || file.response.url;

        // 确保URL格式正确
        if (imgUrl && !imgUrl.startsWith('http')) {
          imgUrl = `${path}${imgUrl.startsWith('/') ? imgUrl : '/' + imgUrl}`;
        }

        if (imgUrl) {
          updateSpecificationField(id, 'image', {
            uid: file.uid,
            name: file.name,
            url: imgUrl,
            status: 'done' as const,
            thumbUrl: imgUrl,
            response: file.response
          });
        } else {
          message.error('获取图片URL失败');
          updateSpecificationField(id, 'image', null);
        }
      } else {
        // 如果没有response，尝试从file本身获取
        const imgUrl = file.url || file.thumbUrl;
        if (imgUrl) {
          updateSpecificationField(id, 'image', {
            uid: file.uid,
            name: file.name,
            url: imgUrl,
            status: 'done' as const,
            thumbUrl: imgUrl
          });
        } else {
          message.error('图片上传失败：无法获取图片URL');
          updateSpecificationField(id, 'image', null);
        }
      }
    } else if (file.status === 'error') {
      message.error('图片上传失败');
      updateSpecificationField(id, 'image', null);
    } else if (file.status === 'removed') {
      updateSpecificationField(id, 'image', null);
    }
  };
  // 基础信息表单
  const renderBasicInfo = () => (
    <div className="tab-content" style={{ padding: '20px' }}>
      {/* 左侧表格与右侧表单布局 */}
      <div style={{ display: 'flex', gap: '20px', marginBottom: '20px' }}>
        {/* 右侧表单区域 */}
        <div style={{ width: '70%' }}>
          <Form form={form} layout="horizontal" colon={false}>
            <Form.Item
              name="category"
              label="商品分类"
              rules={[{ required: true, message: '请选择商品分类' }]}
              style={{ marginBottom: '20px' }}
            >
              <Select placeholder="请选择商品分类" size="large" style={{ width: '100%' }}>
                {categories.map(cat => (
                  <Option key={cat.value} value={cat.value}>{cat.label}</Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="goodsName"
              label="商品名称"
              rules={[{ required: true, message: '请输入商品名称' }]}
              style={{ marginBottom: '20px' }}
            >
              <Input placeholder="请输入商品名称" size="large" style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item
              name="synopsis"
              label="商品简介"
              rules={[{ required: true, message: '请输入商品简介' }]}
              style={{ marginBottom: '20px' }}
            >
              <Input placeholder="请输入商品简介" size="large" style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item
              name="unit"
              label="单位"
              className='margin28'
              rules={[{ required: true, message: '请输入单位' }]}
              style={{ marginBottom: '20px' }}
            >
              <Input placeholder="请输入单位" size="large" style={{ width: '100%' }} />
            </Form.Item>
          </Form>
        </div>
      </div>

      {/* 视频上传区域 - Switch 控制显示隐藏 */}
      <Form form={form} layout="horizontal" colon={false}>
        <Form.Item
          name="hasVideo"
          label="是否添加视频"
          valuePropName="checked"
          style={{ marginBottom: '20px' }}
        >
          <Switch onChange={(checked) => setShowVideoUpload(checked)} />
        </Form.Item>
      </Form>


      {showVideoUpload && (
        <div style={{
          marginBottom: '20px',
          borderRadius: '4px',
        }}>
          <div style={{ marginBottom: '10px' }}>商品视频</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            {videoFile ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <PlayCircleOutlined style={{ fontSize: '24px', color: '#1890ff' }} />
                <span>{videoFile.name}</span>
                <Button type="link" danger onClick={handleDeleteVideo} icon={<DeleteIcon />}>
                  删除
                </Button>
              </div>
            ) : (
              <Upload
                accept="video/mp4,video/avi,video/mov,video/wmv,video/flv,video/webm"
                showUploadList={false}
                beforeUpload={(file) => {
                  // 支持的视频格式
                  const allowedTypes = [
                    'video/mp4',
                    'video/avi',
                    'video/quicktime', // mov
                    'video/x-ms-wmv',
                    'video/x-flv',
                    'video/webm'
                  ];

                  if (!allowedTypes.includes(file.type)) {
                    message.error('只能上传 MP4, AVI, MOV, WMV, FLV, WebM 格式的视频！');
                    return Upload.LIST_IGNORE;
                  }

                  // 文件大小限制（100MB）
                  const maxSize = 100 * 1024 * 1024;
                  if (file.size > maxSize) {
                    message.error('视频大小不能超过100MB！');
                    return Upload.LIST_IGNORE;
                  }

                  return false;
                }}
                onChange={handleVideoUpload}
              >
                <Button icon={<UploadOutlined />} size="large" style={{ background: '#165DFF', color: 'white' }}>点击上传</Button>
              </Upload>
            )}
          </div>
        </div>
      )}

      {/* 图片上传区域 - 左侧单图 右侧多图 */}
      <div style={{ marginBottom: '20px' }}>
        <div style={{ display: 'flex', gap: '150px' }}>
          {/* 左侧单图上传（主图） */}
          <div>
            <Form form={form} layout="horizontal" colon={false}>
              <Form.Item
                name="mainImage"
                label="商品图片"
                rules={[{
                  required: true,
                  validator: (_, value) => {
                    if (mainImageFileList.length === 0) {
                      return Promise.reject(new Error('请上传图片'));
                    }
                    return Promise.resolve();
                  }
                }]}
              >
                <Upload
                  listType="picture-card"
                  fileList={mainImageFileList}
                  onChange={handleMainImageUpload}
                  customRequest={customUploadRequest}
                  accept=".jpg,.jpeg,.png,.gif,.bmp,.webp"
                  beforeUpload={(file) => {
                    // 验证逻辑
                    const fileExtension = file.name.split('.').pop()?.toLowerCase();
                    const allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
                    const isImage = file.type.startsWith('image/');
                    const isValidExtension = allowedExtensions.includes(fileExtension);

                    if (!isImage || !isValidExtension) {
                      message.error('只能上传 JPG, PNG, GIF, BMP, WebP 格式的图片！');
                      return Upload.LIST_IGNORE;
                    }

                    const maxSize = 5 * 1024 * 1024;
                    if (file.size > maxSize) {
                      message.error('图片大小不能超过5MB！');
                      return Upload.LIST_IGNORE;
                    }

                    return true; // 改为返回true，让customRequest处理上传
                  }}
                  maxCount={1}
                  onRemove={() => setMainImageFileList([])} // 添加移除处理
                >
                  {mainImageFileList.length >= 1 ? null : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传图片</div>
                    </div>
                  )}
                </Upload>
              </Form.Item>
            </Form>
          </div>

          {/* 右侧多图上传（详情图） */}
          <div style={{ width: '50%' }}>
            <Form form={form} layout="horizontal" colon={false}>
              <Form.Item
                name="detailImages"
                label="轮播图"
                rules={[{
                  required: true,
                  validator: (_, value) => {
                    if (detailImageFileList.length < 2) {
                      return Promise.reject(new Error('请上传至少两张图片'));
                    }
                    return Promise.resolve();
                  }
                }]}
              >
                <Upload
                  listType="picture-card"
                  fileList={detailImageFileList}
                  onChange={handleDetailImageUpload}
                  customRequest={customUploadRequest} // 添加自定义上传请求
                  accept=".jpg,.jpeg,.png,.gif,.bmp,.webp"
                  beforeUpload={(file) => {
                    // 单文件验证
                    const allowedTypes = [
                      'image/jpeg',
                      'image/jpg',
                      'image/png',
                      'image/gif',
                      'image/bmp',
                      'image/webp'
                    ];

                    if (!allowedTypes.includes(file.type)) {
                      message.error('只能上传 JPG, PNG, GIF, BMP, WebP 格式的图片！');
                      return Upload.LIST_IGNORE;
                    }

                    // 文件大小限制（5MB）
                    const maxSize = 5 * 1024 * 1024;
                    if (file.size > maxSize) {
                      message.error('单张图片大小不能超过5MB！');
                      return Upload.LIST_IGNORE;
                    }

                    return true; // 返回true，让customRequest处理上传
                  }}
                  multiple
                  maxCount={5}
                >
                  {detailImageFileList.length >= 5 ? null : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传轮播图</div>
                    </div>
                  )}
                </Upload>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>

      {/* 状态设置 */}
      <Form form={form} layout="horizontal" colon={false}>
        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
          style={{ marginBottom: '20px' }}
        >
          <Radio.Group>
            <Radio value={1}>上架</Radio>
            <Radio value={0}>下架</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </div>
  );

  // 规格库存表单
  const renderSpecStock = () => (
    <div className="tab-content" style={{ padding: '20px' }}>
      {/* 商品规格选择 */}
      <Form form={form} layout="horizontal" colon={false}>
        <Form.Item
          name="specType"
          label="商品规格"
          rules={[{ required: true, message: '请选择商品规格' }]}
          style={{ marginBottom: '20px' }}
          initialValue="single"
        >
          <Radio.Group
            onChange={(e) => {
              setSpecType(e.target.value);
              // 当切换规格类型时同步更新表单值
              form.setFieldsValue({ specType: e.target.value });

              // 切换规格类型时重置相关数据
              if (e.target.value === 'single') {
                // 切换到单规格时，清空多规格数据
                setSpecInputs([{ id: 1, value: '' }]);
                setSpecifications([{ id: 1, name: '', price: '', originalPrice: '', stock: '', image: null }]);
              } else {
                // 切换到多规格时，设置默认规格
                setSpecInputs([{ id: 1, value: '默认规格' }]);
                setSpecifications([{
                  id: 1,
                  name: '默认规格',
                  price: '',
                  originalPrice: '',
                  stock: '',
                  image: null
                }]);
              }
            }}
            value={specType}
          >
            <Radio value="single">单规格</Radio>
            <Radio value="multiple">多规格</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>

      {/* 单规格显示 */}
      {specType === 'single' && (
        <div>
          <Form form={form} layout="horizontal" colon={false}>
            <Form.Item
              name="price"
              label="售价"
              rules={[{ required: true, message: '请输入售价' }]}
              style={{ marginBottom: '20px' }}
            >
              <InputNumber
                placeholder="0.00"
                style={{ width: '100%' }}
                size="large"
                min={0}
                precision={2}
              />
            </Form.Item>

            <Form.Item
              name="originalPrice"
              label="原价"
              rules={[{ required: true, message: '请输入原价' }]}
              style={{ marginBottom: '20px' }}
            >
              <InputNumber
                placeholder="0.00"
                style={{ width: '100%' }}
                size="large"
                min={0}
                precision={2}
              />
            </Form.Item>

            <Form.Item
              name="stock"
              label="库存"
              rules={[{ required: true, message: '请输入库存' }]}
              style={{ marginBottom: '20px' }}
            >
              <InputNumber
                placeholder="0"
                style={{ width: '100%' }}
                size="large"
                min={0}
              />
            </Form.Item>
          </Form>
        </div>
      )}

      {/* 多规格特有设置 */}
      {specType === 'multiple' && (
        <>
          {/* 规格名称输入区域 */}
          <Form layout="horizontal" colon={false}>
            <Form.Item
              name="specName"
              label="规格"
              rules={[{ required: true, message: '请输入规格名称' }]}
              style={{ marginBottom: '20px' }}
            >
              <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
                <Button
                  type="primary"
                  onClick={addSpecInput}
                  icon={<PlusOutlined />}
                  style={{ marginRight: 8 }}
                >
                  添加新规格
                </Button>

                {/* 动态生成的规格输入框 */}
                {specInputs.map((input) => (
                  <div key={input.id} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <Input
                      placeholder="请输入规格名称"
                      value={input.value}
                      onChange={(e) => updateSpecInput(input.id, e.target.value)}
                      style={{ width: '180px' }}
                      suffix={
                        specInputs.length > 1 && (
                          <DeleteOutlined
                            onClick={() => removeSpecInput(input.id)}
                            style={{ color: '#ff4d4f', cursor: 'pointer' }}
                          />
                        )
                      }
                    />
                  </div>
                ))}
              </div>
            </Form.Item>
          </Form>

          {/* 批量设置表格 */}
          <div style={{ marginBottom: 20 }}>
            <div style={{ marginBottom: 12 }}>批量设置</div>
            <Table
              dataSource={specifications}
              pagination={false}
              bordered
              rowKey="id"
              columns={[
                {
                  align: 'center',
                  title: '图片',
                  dataIndex: 'image',
                  width: 100,
                  render: (image: any, record: any) => (
                    <Upload
                      style={{ width: '60px', height: '60px' }}
                      listType="picture-card"
                      fileList={image ? [image] : []}
                      onChange={(info) => handleSpecificationImageUpload(record.id, info)}
                      customRequest={customUploadRequest}
                      accept=".jpg,.jpeg,.png,.gif,.bmp,.webp"
                      beforeUpload={(file) => {
                        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
                        if (!allowedTypes.includes(file.type)) {
                          message.error('只能上传图片格式文件！');
                          return Upload.LIST_IGNORE;
                        }
                        const maxSize = 5 * 1024 * 1024;
                        if (file.size > maxSize) {
                          message.error('图片大小不能超过5MB！');
                          return Upload.LIST_IGNORE;
                        }
                        return true;
                      }}
                      maxCount={1}
                      onRemove={() => {
                        updateSpecificationField(record.id, 'image', null);
                      }}
                      showUploadList={{
                        showPreviewIcon: true,
                        showRemoveIcon: true,
                        showDownloadIcon: false,
                      }}
                    >
                      {image ? null : (
                        <div style={{
                          display: 'flex',
                          flexDirection: 'column',
                          alignItems: 'center',
                          justifyContent: 'center',
                          height: '100%'
                        }}>
                          <PlusOutlined />
                          <div style={{ marginTop: 4, fontSize: 12 }}>上传图片</div>
                        </div>
                      )}
                    </Upload>
                  )
                },
                {
                  align: 'center',
                  title: '售价',
                  dataIndex: 'price',
                  render: (price: string, record: any) => (
                    <InputNumber
                      placeholder="请输入价格"
                      value={price}
                      onChange={(value) => updateSpecificationField(record.id, 'price', value)}
                      style={{ width: '100%' }}
                      min={0}
                      precision={2}
                      className={!price && specifications.length > 0 ? 'error-input' : ''}
                    />
                  )
                },
                {
                  align: 'center',
                  title: '原价',
                  dataIndex: 'originalPrice',
                  render: (originalPrice: string, record: any) => (
                    <InputNumber
                      placeholder="请输入原价"
                      value={originalPrice}
                      onChange={(value) => updateSpecificationField(record.id, 'originalPrice', value)}
                      style={{ width: '100%' }}
                      min={0}
                      precision={2}
                      className={!originalPrice && specifications.length > 0 ? 'error-input' : ''}
                    />
                  )
                },
                {
                  align: 'center',
                  title: '库存',
                  dataIndex: 'stock',
                  render: (stock: string, record: any) => (
                    <InputNumber
                      placeholder="请输入库存"
                      value={stock}
                      onChange={(value) => updateSpecificationField(record.id, 'stock', value)}
                      style={{ width: '100%' }}
                      min={0}
                      className={!stock && specifications.length > 0 ? 'error-input' : ''}
                    />
                  )
                },
                {
                  align: 'center',
                  title: '操作',
                  render: (_: any, record: any) => (
                    <div style={{ display: 'flex', gap: '15px', justifyContent: 'center' }}>
                      <Button
                        type="link"
                        danger
                        style={{ padding: '0 4px', border: '1px solid #ff4d4f' }}
                        size="small"
                        onClick={() => removeSpecification(record.id)}
                      >
                        删除
                      </Button>
                      <Button
                        type="link"
                        style={{ padding: '0 4px', border: '1px solid #1890ff' }}
                        size="small"
                        onClick={() => resetSpecification(record.id)}
                      >
                        重置
                      </Button>
                    </div>
                  )
                }
              ]}
            />
          </div>
        </>
      )}
    </div>
  );


  // 物流设置表单
  const renderLogistics = () => (
    <div className="tab-content" style={{ padding: '20px' }}>
      <div style={{}}>
        <Form form={form} layout="horizontal" colon={false}>
          <Form.Item
            name="shipAddress"
            label="发货地址"
            rules={[{ required: true, message: '请输入发货地址' }]}
            style={{ marginBottom: '20px' }}
          >
            <Input placeholder="请输入发货地址" size="large" />
          </Form.Item>

          <Form.Item
            name="shippingFee"
            label="运费"
            className='margin28'
            rules={[{ required: true, message: '请输入运费' }]}
            style={{ marginBottom: '20px' }}
          >
            <InputNumber
              placeholder="0.00"
              style={{ width: '100%' }}
              size="large"
              min={0}
              precision={2}
            />
          </Form.Item>
        </Form>
      </div>
    </div>
  );

  // 营销设置表单
  const renderMarketing = () => (
    <div className="tab-content" style={{ padding: '20px' }}>
      <div style={{}}>
        <Form form={form} layout="horizontal" colon={false}>
          <Form.Item
            name="sort"
            label="排序"
            className='margin28'
            rules={[{ required: true, message: '请输入排序号' }]}
            style={{ marginBottom: '20px' }}
          >
            <InputNumber
              placeholder="0"
              style={{ width: '100%' }}
              size="large"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="sales"
            label="已售数量"
            rules={[{ required: true, message: '请输入已售数量' }]}
            style={{ marginBottom: '20px' }}
          >
            <InputNumber
              placeholder="0"
              style={{ width: '100%' }}
              size="large"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="recommendation"
            label="商品推荐"
            rules={[{ required: true, message: '请至少选择一项推荐' }]}
            style={{ marginBottom: '20px' }}
          >
            <Checkbox.Group>
              <div style={{ display: 'flex', gap: '8px' }}>
                <Checkbox value="hot">热销商品</Checkbox>
                <Checkbox value="recommend">为您推荐</Checkbox>
                <Checkbox value="guess">猜你喜欢</Checkbox>
              </div>
            </Checkbox.Group>
          </Form.Item>

          <Form.Item
            name="keywords"
            label="关键字"
            rules={[{ required: true, message: '请输入关键字' }]}
            style={{ marginBottom: '20px', marginLeft: '14px' }}
          >
            <Input placeholder="请输入关键字" size="large" />
          </Form.Item>
        </Form>
      </div>
    </div>
  );

  const tabItems: TabsProps['items'] = [
    {
      key: '1',
      label: '基础信息',
      children: renderBasicInfo(),
    },
    {
      key: '2',
      label: '规格库存',
      children: renderSpecStock(),
    },
    {
      key: '3',
      label: '商品详情',
      children: (
        <div className="tab-content" style={{ padding: '20px' }}>
          <Form form={form} layout="horizontal" colon={false}>
            <Form.Item
              name="descriptiones"
              label="商品详情"
              rules={[{ required: true, message: '请输入商品详情' }]}
            >
              <UEditor ref={ueditorRef1} />
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      key: '4',
      label: '产品参数',
      children: (
        <div className="tab-content" style={{ padding: '20px' }}>
          <Form form={form} layout="horizontal" colon={false}>
            <Form.Item
              name="params"
              label="产品参数"
              rules={[{ required: true, message: '请输入产品参数' }]}
            >
              <UEditor ref={ueditorRef2} />
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      key: '5',
      label: '物流设置',
      children: renderLogistics(),
    },
    {
      key: '6',
      label: '营销设置',
      children: renderMarketing(),
    },
  ];

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key: React.Key) => {
    try {
      const row = await form.validateFields();
      // 这里调用更新接口
      console.log('保存数据:', row);
      setEditingKey('');
    } catch (errInfo) {
      console.log('验证失败:', errInfo);
    }
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const { initialState } = useModel('@@initialState');

  // 列表视图
  const renderListView = () => (
    <div style={{ padding: '20px', backgroundColor: 'white' }}>
      {/* 标题区域 */}
      <div className='teacher'>商品列表</div>

      {/* 搜索区域 */}
      <div className='search'>
        <Form
          form={searchForm}
          layout="horizontal"
          colon={false}
          style={{ width: '85%' }}
        >
          {/* 第一行 */}
          <div className='searchList'>
            <Form.Item name="name" label="商品名称">
              <Input placeholder="请输入商品名称" style={{ width: '225px' }} />
            </Form.Item>
            <Form.Item name="keyword" label="关键字">
              <Input placeholder="请输入关键字" style={{ width: '225px', marginLeft: '14px' }} />
            </Form.Item>
            <Form.Item name="category" label="商品分类">
              <Select
                placeholder="请选择商品分类"
                style={{ width: '225px' }}
                loading={loading}
                allowClear
              >
                {categories.map(category => (
                  <Option key={category.value} value={category.value}>
                    {category.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>

          {/* 第二行 */}
          <div className='searchList'>
            <Form.Item name="description" label="商品简介">
              <Input placeholder="请输入商品简介" style={{ width: '225px' }} />
            </Form.Item>
            <Form.Item name="specType" label="规格">
              <Select placeholder="请选择规格" style={{ width: '225px', marginLeft: '28px' }}>
                <Option value="1">单规格</Option>
                <Option value="0">多规格</Option>
              </Select>
            </Form.Item>
            <Form.Item name="recommendation" label="商品推荐">
              <Select placeholder="请选择商品推荐" style={{ width: '225px' }}>
                <Option value="1">热销商品</Option>
                <Option value="2">为您推荐</Option>
                <Option value="3">猜你喜欢</Option>
              </Select>
            </Form.Item>
          </div>
        </Form>

        {/* 竖线分割 */}
        <div style={{ height: '100px', width: '1px', background: '#999999' }}></div>

        {/* 按钮区域 */}
        <div className='button'>
          <Button
            type="primary"
            onClick={handleSearch}
            style={{ width: '100px', background: '#165DFF' }}
            icon={<SearchOutlined />}
          >
            查询
          </Button>
          <Button
            onClick={handleReset}
            style={{ width: '100px' }}
            icon={<ReloadOutlined />}
          >
            重置
          </Button>
        </div>
      </div>
      <div className='line'></div>

      {/* 操作按钮区域 */}
      <div className='buttonBox'>
        <div className='refresh'>
          <Button type="primary" icon={<PlusOutlined />} onClick={showAddView}>
            新建
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            style={{ background: 'red', color: 'white' }}
            onClick={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            批量删除
          </Button>
          <Button
            icon={<DownloadOutlined />}
          >
            批量下架
          </Button>
        </div>
        <div>
          <img src="./refresh.png" alt="refresh" onClick={handleReset} className='w20' />
        </div>
      </div>

      {/* 表格区域 */}
      <div className='table'>
        <Table
          dataSource={data}
          columns={columns}
          rowKey="key"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          onChange={handleTableChange}
          rowSelection={rowSelection}
          scroll={{ x: 1200 }}
        />
      </div>
    </div>
  );

  // 新增/编辑视图
  const renderEditView = () => (
    <div>
      {/* 标题区域 */}
      <div className='teacher'>
        <Button
          type="link"
          icon={<LeftOutlined />}
          onClick={showListView}
          style={{ marginRight: '16px', color: '#000' }}
        >
          返回
        </Button>
        {currentGoodsId ? '编辑商品' : '新增商品'}
      </div>

      <div className='line'></div>

      {/* 选项卡区域 */}
      <Tabs
        activeKey={tabActiveKey}
        items={tabItems}
        onChange={handleTabChange}
        tabBarStyle={{ marginBottom: 20 }}
      />

      {/* 底部按钮区域 */}
      <div style={{ display: 'flex', gap: '20px', marginTop: 30 }}>
        {currentStep > 0 && (
          <Button
            size="large"
            onClick={handlePrev}
            style={{ width: '120px' }}
          >
            上一步
          </Button>
        )}
        {currentStep < 5 ? (
          <Button
            type="primary"
            size="large"
            onClick={handleNext}
            style={{ width: '120px', background: '#165DFF' }}
          >
            下一步
          </Button>
        ) : (
          <Button
            type="primary"
            size="large"
            onClick={handleSave}
            style={{ width: '120px', background: '#165DFF' }}
          >
            保存
          </Button>
        )}
      </div>
    </div>
  );

  return (
    <div className="goods-list-container">
      {currentView === 'list' ? renderListView() : renderEditView()}
    </div>
  );
};

export default GoodsList;
